import { login, logout, getInfo } from '@/api/manager/user'
import { getToken, setToken, removeToken ,getSysMgr,setSysMgr,removeSysMgr} from '@/utils/auth'
import router, { resetRouter } from '@/router'

const state = {
  token: getToken(),
  name: '',
  avatar: '',
  introduction: '',
  sysMgr: getSysMgr(),
  menuList: []
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, menuList) => {
    state.menuList = menuList
  },
  SET_SYS_MGR: (state, sysMgr)=>{
    state.sysMgr = sysMgr
  }
}

const actions = {
  // user login
  login ({ commit }, userInfo) {
    return new Promise((resolve, reject) => {
      login(userInfo).then(response => {
        commit('SET_TOKEN', response.token)
        setToken(response.token)
        removeSysMgr()
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo ({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {

        if (!response) {
          reject('验证失败,请重新登录.')
        }
        const { menuList, user} = response
        commit('SET_ROLES', menuList)
        commit('SET_NAME', user.userAccount)
        commit('SET_INTRODUCTION', user.userDesc)
        resolve(response)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout ({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        removeToken()
        resetRouter()

        // reset visited views and cached views
        // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
        dispatch('tagsView/delAllViews', null, { root: true })

        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken ({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      removeToken()
      resolve()
    })
  },

  // dynamically modify permissions
  initRouter ({ commit, state, dispatch }) {
    return new Promise(async (resolve, reject)  => {
      if(getToken()){
        try{
          let userInfo = await dispatch('getInfo')
          let menuList = userInfo.menuList
          resetRouter()
          // generate accessible routes map based on menuList
          const accessRoutes = await dispatch('permission/generateRoutes',{menuList,sysMgr:state.sysMgr},{root:true})
          // dynamically add accessible routes
          router.addRoutes(accessRoutes)
          // reset visited views and cached views
          dispatch('tagsView/delAllViews', null, { root: true })
          resolve()
        }catch (e) {
          commit('SET_TOKEN', '')
          commit('SET_ROLES', [])
          removeToken()
          reject(e)
        }

      }
    })
  },
  // 转为后台  或者转到前台  sys
  sysManage({ commit, state, dispatch },flag) {
    return new Promise(async resolve => {
      commit('SET_SYS_MGR', flag)
      // 如果使用false值放到cookie会变成string  false时直接删除
      if(flag){
        setSysMgr(flag)
      }else {
        removeSysMgr()
      }
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
